package com.jielihaofeng.nio.filechannel;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

/**
 * @description 文件channel传输
 * @author Johnnie Wind
 * @date 2021/10/10 15:07
 */
public class TestFileChannelTransferTo {

    public static void main(String[] args) {
        fileTransfer();
//        over2gFileTransfer();
    }

    private static void fileTransfer() {
        long start = System.nanoTime();
        try (
                FileChannel from = new FileInputStream("data.txt").getChannel();
                FileChannel to = new FileOutputStream("to.txt").getChannel();
        ) {
            from.transferTo(0, from.size(), to);

        } catch (IOException e) {
            e.printStackTrace();
        }
        long end = System.nanoTime();
        System.out.println("transferTo 用时：" + (end - start) / 1000_000.0);
    }

    private static void over2gFileTransfer() {
        try (
                FileChannel from = new FileInputStream("data.txt").getChannel();
                FileChannel to = new FileOutputStream("to.txt").getChannel();
        ) {
            // 效率比文件输入输出流效率高，底层会利用操作系统的零拷贝进行优化，2g 数据
            long size = from.size();
            // left 变量代表还剩余多少字节没有传输
            for (long left = size; left > 0; ) {
                System.out.println("position:" + (size - left) + " left:" + left);
                left -= from.transferTo(size - left, left, to);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
